<extend name="./base" />
<block name="pageContent">
    <link rel="stylesheet" href="/Public/AdminTpl/css/summarize.css">
    <link rel="stylesheet" href="/Public/AdminTpl/autoComplete/autocomplete.css?v=32">
    <div class="main-content">
        <div class="breadcrumbs" id="breadcrumbs">
            <ul class="breadcrumb no-margin-left">
                <li>
                    <a>当前股票：<em style="color: #ab1ba7" id="stockName"></em></a>
                </li>
                <li>
                    <a>当前允许委托最低价：<b style="color: forestgreen" id="stockMinPrice"></b></a>
                </li>
                <li>
                    <a>当前允许委托最高价：<b style="color: red" id="stockMaxPrice"></b></a>
                </li>
                <li>
                    <a>当前服务器时间：<em style="color: #10a1e7" id="dateTime"></em></a>
                </li>
                <li>
                    <button type="button" onclick="delegateList()" class="btn" style="border-radius: 1.8rem; background: #0451d7!important;border:1px solid #0451d7;margin-left: 20px;">委托记录</button>
                </li>
            </ul>
        </div>
        <!--页面容器-->
        <div class="page-content">
            <div class="row">
                <div class="col-xs-12 vessel-box">
                    <!--提现申请-->
                    <div class="row vessel-bot business-title">
                        <div class="col-lg-2 padding0">
                            <div class="business-title-h3">
                                当前委托<b style="color: forestgreen"> 卖出</b>
                            </div>
                            <div class="business-list-table ">
                                <table style="table-layout: fixed;" width="100%" border="0" cellpadding="0" cellspacing="0">
                                    <thead>
                                    <tr class="back-gray font-size16 color-gray6">
                                        <th>五档</th>
                                        <th>价格</th>
                                        <th>委托量</th>
                                    </tr>
                                    </thead>
                                    <tbody id="salefList" style="cursor: pointer">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="col-lg-2 ">
                            <div class="business-title-h3">
                                当前委托<b style="color: red"> 买入</b>
                            </div>
                            <div class="business-list-table ">
                                <table style="table-layout: fixed;" width="100%" border="0" cellpadding="0" cellspacing="0">
                                    <thead>
                                    <tr class="back-gray font-size16 color-gray6">
                                        <th>五档</th>
                                        <th>价格</th>
                                        <th>委托量</th>
                                    </tr>
                                    </thead>
                                    <tbody id="buyfList" style="cursor: pointer">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="col-lg-8" id="tradekline" style="height: 350px">
                        </div>
                    </div>
                    <div class="row vessel-bot business-title">
                        <div class="col-lg-4 padding0">
                            <div class="business-title-h3">
                                委托买卖
                            </div>
                            <div class="s_form-textarea">
                                <span>股票代码 </span>
                                <div id="search-form" class="s_form-width"></div>
                                <div id="message"></div>
                            </div>
                            <div class="s_form-textarea">
                                <span>价格</span>
                                <input type="number" id="inputPrice" class="s_form-width" datatype="*" placeholder="请输入价格"/>
                            </div>
                            <div class="s_form-textarea">
                                <span>数量</span>
                                <input type="number" id="inputNum" class="s_form-width" datatype="*" placeholder="请输入数量"/>
                            </div>
                            <div style="margin: 50px 80px;">
                                <button onclick="buy()" type="button"  class="btn " style="width: 150px; border-radius: 2rem; background: #d70417!important;border:1px solid #d70417;margin-left: 20px;">确认买入</button>
                                <button onclick="sale()" type="button"  class="btn " style="width: 150px; border-radius: 2rem; background: #04d728!important;border:1px solid #04d728;margin-left: 20px;">确认卖出</button>
                            </div>
                        </div>
                        <div class="col-lg-8" id="tradeline" style="height: 280px">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row" id="delegateDiv" style="display: none">
            <div class="col-xs-12">
                <table id="sample-table-1"
                       class="table table-hover">
                    <thead>
                    <tr>
                        <th class="center">买卖方向</th>
                        <th class="center">股票名称</th>
                        <th class="center">委托价</th>
                        <th class="center">委托数</th>
                        <th class="center">成交数量</th>
                        <th class="center">操作</th>
                    </tr>
                    </thead>
                    <tbody id="delegateTr">
                    </tbody>
                </table>
            </div>
        </div>

    </div>
    <script src="/Public/AdminTpl/js/echarts.min.js"></script>
    <script src="/Public/AdminTpl/autoComplete/autocomplete.js?v=3"></script>
    <script src="/Public/AdminTpl/js/yltcrypt.js"></script>
    <script src="/Public/AdminTpl/js/ws.js"></script>
    <script src="/Public/AdminTpl/js/layer/layer.js"></script>
    <script>
        var openId = '{$openId}';
        var sresArr = {$sresArr};
        var proposals = {$snameArr};
        var serverApi = '{$serverApi}';
        var currentSid = 0;
        var currentStock = '';
        var socketUrl = '{$socketUrl}';

        var tradekline = echarts.init(document.getElementById("tradekline"));
        var tradeline = echarts.init(document.getElementById("tradeline"));

        //切换股票
        function changeStock() {
            if(currentStock){
                $('#stockName').text(currentStock);
                currentSid = sresArr[currentStock];
                fiveData();
                handcip();

                kline();//K线图
                line();//分时图

                //建立websockt连接
                var ct = '?ct=fiveTradeData-'+currentSid+'@tradeLine-'+currentSid;
                WS.init(socketUrl+ct);
            }
        }

        //股票五档信息(ws推送)
        function fiveData() {
            $.post(serverApi+'/trade/stockFiveData',{sid:currentSid},function(data){
                var buyList = data.buy;
                var htmlStr = '';
                for(var i=0;i<buyList.length;i++){
                    htmlStr += '<tr onclick="changePrice(this)" class="color-gray9"><td>'+buyList[i].name+'</td><td>'+buyList[i].price+'</td><td>'+buyList[i].num+'</td></tr>';
                }
                $('#buyfList').html(htmlStr);

                var saleList = data.sale;
                htmlStr = '';
                for(var i=0;i<saleList.length;i++){
                    htmlStr += '<tr onclick="changePrice(this)" class="color-gray9"><td>'+saleList[i].name+'</td><td>'+saleList[i].price+'</td><td>'+saleList[i].num+'</td></tr>';
                }
                $('#salefList').html(htmlStr);
            });
        }
        //股票盘口信息(ws推送)
        function handcip() {
            $.post(serverApi+'/trade/stockHandicap',{sid:currentSid},function(data){
                $('#stockMinPrice').text(data.data.min_price);
                $('#stockMaxPrice').text(data.data.max_price);
            });
        }


        function splitData(rawData) {
            var categoryData = [];
            var values = [];
            var macds = [];
            var difs = [];
            var deas = [];
            for (var i = 0; i < rawData.length; i++) {
                categoryData.push(rawData[i].splice(0, 1)[0]);
                values.push(rawData[i])
                macds.push(rawData[i][4]);
            }
            return {
                categoryData: categoryData,
                values: values,
                macds: macds
            };
        }
        function calculateMA(dayCount) {
            var result = [];
            for (var i = 0, len = data0.values.length; i < len; i++) {
                if (i < dayCount) {
                    result.push('-');
                    continue;
                }
                var sum = 0;
                for (var j = 0; j < dayCount; j++) {
                    sum += data0.values[i - j][1]*1;
                }
                result.push(sum / dayCount);
            }
            return result;
        }
        //股票日K(ws推送)
        function kline() {
            $.post(serverApi+'/trade/stockKline',{sid:currentSid,type:2},function(data){
                if(data.code == 0){
                    createKline(data.data);
                }
            });
        }
        function createKline(datas){
            data0=splitData(datas);
            klineOpt = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                grid:[ {
                    left: '3%',
                    top: '0',
                    height: '70%'
                },{
                    left: '3%',
                    right: '10%',
                    top: '80%',
                    height: '15%'
                }],
                xAxis: [{
                    type: 'category',
                    data: data0.categoryData,
                    scale: true,
                    boundaryGap: false,
                    axisLine: {
                        onZero: false,
                        lineStyle:{
                            color:'red',
                        }
                    },
                    splitLine: {
                        show: false
                    },
                    splitNumber: 20
                },{
                    type: 'category',
                    gridIndex: 1,
                    data: data0.categoryData,
                    axisLabel: {show: false},

                }],
                yAxis:[ {
                    scale: true,
                    splitArea: {
                        show: true
                    },
                    axisLine:{
                        lineStyle:{
                            color:'red',
                        }
                    },
                    position: 'right'
                },{
                    gridIndex: 1,
                    splitNumber: 3,
                    axisLine: {onZero: false},
                    axisTick: {show: false},
                    splitLine: {show: false},
                    axisLabel: {show: true},
                    axisLine:{

                        lineStyle:{
                            color:'red'

                        }
                    },
                    position: 'right'
                }],
                dataZoom: [{
                    type: 'inside',
                    start: 100,
                    end: 0
                }, {
                    show: false,
                    type: 'slider',
                    y: '90%',
                    start: 50,
                    end: 100
                },{
                    show: false,
                    xAxisIndex: [0, 1],
                    type: 'slider',
                    start: 20,
                    end: 100
                }],
                series: [{
                    name: '股票名称',
                    type: 'candlestick',
                    data: data0.values
                }, {
                    name: 'MA5',
                    type: 'line',
                    data: calculateMA(5),
                    smooth: true,
                    lineStyle: {
                        normal: {
                            opacity: 0.5
                        }
                    }
                }, {
                    name: 'MA10',
                    type: 'line',
                    data: calculateMA(10),
                    smooth: true,
                    lineStyle: {
                        normal: {
                            opacity: 0.5
                        }
                    }
                }, {
                    name: 'MA20',
                    type: 'line',
                    data: calculateMA(20),
                    smooth: true,
                    lineStyle: {
                        normal: {
                            opacity: 0.5
                        }
                    }
                }, {
                    name: 'MA30',
                    type: 'line',
                    data: calculateMA(30),
                    smooth: true,
                    lineStyle: {
                        normal: {
                            opacity: 0.5
                        }
                    }
                },{
                    name: '交易量',
                    type: 'bar',
                    xAxisIndex:1,
                    yAxisIndex: 1,
                    data: data0.macds,
                    itemStyle: {
                        normal: {
                            color: function(params) {
                                var colorList;
                                if (params.data >= 0) {
                                    colorList = '#ef232a';
                                } else {
                                    colorList = '#14b143';
                                }
                                return colorList;
                            },
                        }
                    }
                }
                ]
            };
            tradekline.setOption(klineOpt);
        }

        //股票分时图
        var fsLineTimes,fsLinePrice;
        function line() {
            $.post(serverApi+'/trade/stockKline',{sid:currentSid,type:1},function(data){
                if(data.code == 0){
                    fsLineTimes=data.data.times;
                    fsLinePrice=data.data.prices;
                    createLine(fsLineTimes,fsLinePrice);
                }
            });
        }
        function createLine(xdata,sdata) {
            var lineOpt = {
                title: {
                    text: '分时图',
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis:  {
                    type: 'category',
                    data: xdata
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                series: [
                    {
                        name:'成交价',
                        type:'line',
                        data:sdata,
                    }
                ]
            };
            tradeline.setOption(lineOpt);
        }

        //买入
        function buy() {
            var inputPrice = $('#inputPrice').val();
            var inputNum = $('#inputNum').val();
            if(!currentSid || !inputPrice || !inputNum){
                layer.msg('委托信息不完整', {icon: 5,time: 1500});
                return;
            }
            $.post(serverApi+'/trade/buy',{
                openId:openId,
                sid:currentSid,
                quanlity:inputNum,
                price:inputPrice,
                token:yltcrypt.cpt(openId)
            },function(data){
                if(data.code == 0){
                    layer.msg('委托成功', {icon: 6,time: 1500});
                }else{
                    layer.msg(data.msg, {icon: 5,time: 1500});
                }
            });
        }
        //卖出
        function sale() {
            var inputPrice = $('#inputPrice').val();
            var inputNum = $('#inputNum').val();
            if(!currentSid || !inputPrice || !inputNum){
                layer.msg('委托信息不完整', {icon: 5,time: 1500});
                return;
            }
            $.post(serverApi+'/trade/sale',{
                openId:openId,
                sid:currentSid,
                quanlity:inputNum,
                price:inputPrice,
                token:yltcrypt.cpt(openId)
            },function(data){
                if(data.code == 0){
                    layer.msg('委托成功', {icon: 6,time: 1500});
                }else{
                    layer.msg(data.msg, {icon: 5,time: 1500});
                }
            });
        }

        function changePrice(that) {
            var element = $(that).find('td').eq(1);
            $('#inputPrice').val(element.text());
        }

        //委托列表

        function delegateList() {
            $.post(serverApi+'/trade/delegateList',{
                openId:openId,
                token:yltcrypt.cpt(openId)
            },function(data){
                if(data.code == 0){
                    var dhtmlStr = '';
                    var datas = data.data;
                    for(var i=0;i<datas.length;i++){
                        var tradePect = datas[i].type==1 ? '买入' : '卖出';
                        dhtmlStr+='<tr class="s_tr-vertical" ><td class="center">'+tradePect+'<br/>'+datas[i].addtime+'</td><td class="center">'+datas[i].sname+'<br/>'+datas[i].sno+'</td><td class="center">'+datas[i].delegatePrice+'</td><td class="center">'+datas[i].delegateNum+'</td><td class="center">'+datas[i].dealNum+'</td><td class="center"><button class="btn" style=" border-radius: 2rem; background: #2f74db!important;border:1px solid #2f74db;margin-left: 20px;" onclick="delDelegate('+datas[i].did+',this)">撤销</button></td></tr>';
                    }
                    $('#delegateTr').html(dhtmlStr);
                    layer.open({
                        type: 1,
                        shade: false,
                        title: false,
                        content: $('#delegateDiv'),
                        area: ['893px', '600px']
                    });
                }else{
                    layer.msg(data.msg, {icon: 5,time: 1500});
                }
            });
        }
        //撤销委托
        function delDelegate(did,that) {
            $.post(serverApi+'/trade/cancle',{
                openId:openId,
                did:did,
                token:yltcrypt.cpt(openId)
            },function(data){
                if(data.code==0){
                    $(that).parents('tr').remove();
                }
            });
        }
        
        //所有股票
        $('#search-form').autocomplete({
            hints: proposals,
            width: 300,
            height: 30,
            showButton:false,
            onSubmit: function(text){
                $('#message').html('Selected: <b>' + text + '</b>');
            }
        });

        //服务器当前时间
        var timeNow = {$timeNow};
        function startTime(){
            var today=new Date(timeNow);
            var yyyy = today.getFullYear();
            var MM = checkTime(today.getMonth()+1);
            var dd = checkTime(today.getDate());
            var hh = checkTime(today.getHours());
            var mm = checkTime(today.getMinutes());
            var ss = checkTime(today.getSeconds());
            var dateTime = yyyy+"-"+MM +"-"+ dd +" " + hh+":"+mm+":"+ss;
            setTimeout('startTime()',1000);
            timeNow += 1000;
            $('#dateTime').text(dateTime);
        }
        function checkTime(i){
            if (i<10){i="0" + i;}return i;
        }
        startTime();
    </script>
</block>